<template>
  <div>
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>搜索</span>
      </div>
      <div class="text item">
        <xdh-form ref="form" class="design-form" v-bind="form" :model="model" design-mode :load="load">
          <draggable :options="dragOptions2" @add="onAdd" @sort="onSort">
            <transition-group class="form-list-group" type="transition" :name="'flip-list'" tag="div" style="min-height:100px">
              <template v-for="(element,index) in sortable_item[0]['content']">
                <TableRenders :key="element.prop" :index="index" :item="element" @handleChangeVal="val => handleChangeVal(val,element)" />
              </template>
            </transition-group>
          </draggable>
        </xdh-form>
      </div>
    </el-card>

    <el-card shadow="never" style="margin-top:20px;">
      <div slot="header" class="clearfix">
        <span>列表</span>
      </div>
      <div class="text item">

        <div class="cont">

            <el-table ref="dragTable" id="crTable" row-key="id" empty-text='拖动左侧的组件到表格中' :key="tablekey" :border='true' :data="formData.domains" class="tb-edit" style="width: 100%" highlight-current-row>
              <template v-for="(item,index) in sortable_items">
                <el-table-column align="center" :label="item.label" :key="item.prop" v-bind="item">
                  <template slot="header">
                    <div class="headeritem">
                      <span>{{item.label}}</span>
                      <i class="el-icon-setting icons" @click.stop="handleEditItem(item,index)"></i>
                      <i class="el-icon-delete icons" @click.stop="removeItem(item)"></i>
                    </div>
                  </template>
                  <template slot-scope="scope">
                   <xdh-form ref="form" class="design-form" v-bind="form" :model="tableModel" design-mode>
                      <xdh-form-item v-bind="clone(item)" label="" :labelWidth="'0px'" :type="item.type" :prop="item.prop" >
                      </xdh-form-item>
                    </xdh-form>
                  </template>
                </el-table-column>
              </template>
            </el-table>


        </div>
      </div>
    </el-card>

  </div>
</template>

<script>
import XdhForm from '@/widgets/xdh-form'
import XdhFormItem from '@/widgets/xdh-form/xdh-form-item'
import { mapState, mapGetters } from 'vuex'
import draggable from 'vuedraggable'
import modules from '@/widgets/helper/setting'
import TableRenders from '@/widgets/components/public/tableRenders'

import Sortable from 'sortablejs'

export default {
  name: 'Tables',
  components: {
    draggable, XdhForm, XdhFormItem, TableRenders
  },
  props: {
    field: {
      type: String,
      default: () => {
        return ''
      }
    },
  },
  computed: {
    ...mapState({
      Config: state => state.Config,
      RootNodeInfo: state => state.RootNodeInfo,
      form: state => state.formModel,
      fields: state => state.fields,
      sortable_item: state => state.fields,
      tableField: state => state.tableField,
      // sortable_items: state => state.tableField,
      editField: state => state.editField
    }),
    ...mapGetters(['model','tableModel']),
    sortable_items: {
      get() {
        console.log(this.$store.state.tableField)
        return this.$store.state.tableField;
      },
      set() {

      }

    },
    dragOptions2() {
      return {
        animation: 0,
        ghostClass: 'ghost',
        group: {
          // 只允许放置shared的控件,禁止pull
          put: ['shared']
        }
      }
    },
    contdivstyle() {
      let obj = {}
      obj.background = this.drag3 === '1' ? 'rgba(0,0,0,0.1)' : 'rgba(0,0,0,0.2)'
      // 左侧或者 中间拖动的时候 要 大等于 10
      // obj['z-index'] = 100;//this.drag1 !== '1' ? 100 : -1

      return obj
    }
  },
  data() {
    return {
      tablekey: 'tablekey' + new Date().getTime(),
      formData: {
        domains: []
      },
      dynamicValidateForm: {
        domains: []
      },
      load: modules['dict'].load
    };
  },
  mounted() {
    this.setCreate();
    this.setSort();
  },
  methods: {
    setCreate() {
      setTimeout(() => {
        const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper')[0];
        this.sortable = new Sortable(el, {
          group: {
            // 只允许放置shared的控件,禁止pull
            put: ['shared']
          },
          sort: false,
          onAdd: (e) => {
            this.setSort();
            console.log(e, '+++++++++++++++++++++', e.newIndex)
            const item = e.item._underlying_vm_
            if (item) {
              this.handleDrops(item, e.newIndex)
            }
          }
        })

      })
    },
    setSort() {
      setTimeout(() => {
        const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__header-wrapper tr')[0];
        this.sortable = Sortable.create(el, {
          ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
          onSort: (e) => {
            this.onTableSort(e)
          },
        })
      })
    },
    submitForm(formName) {
      console.log(this.dynamicValidateForm)
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(this.dynamicValidateForm)
          alert("submit!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    removeDomain(item) {
      var index = this.dynamicValidateForm.domains.indexOf(item);
      if (index !== -1) {
        this.dynamicValidateForm.domains.splice(index, 1);
      }
    },
    handleEditItem(item, index) {
      console.error(item, "12321321321")
      item.index = index;
      let info = Object.assign({}, item);
      // this.$store.dispatch('user/setNodeinfo', info);
      this.$store.commit('setEditTableField', info)
      console.log(info)
      console.log('handleEditItem', this.$store.getters, 8888888888);
    },
    removeItem(item) {
      const isDepend = !!this.tableField.find(n => n.depend === item.prop)
      if (isDepend) {
        this.$message.warning('该字段被其他字段依赖，不能删除')
        return
      }
      this.$store.commit('setEditTableField', null)
      this.$store.commit('removeTableField', item)
    },
    onAdd(e) {
      console.log(this.tab_id)
      const item = e.item._underlying_vm_
      if (item) {
        this.handleDrop(item, e.newIndex)
      }
    },
    handleDrops(item, index) {
      console.log(item, index)
      if (item) {
        const defaultName = `${item.type}_${new Date().getTime()}`
        const newItem = {
          ...item,
          label: item.title,
          prop: defaultName,
          value: item.value,
          type: item.type,
        }
        console.log(newItem)
        this.$store.commit('addTableField', { field: newItem, index: index })
      }
    },
    clone(data) {
      console.log('clone')
      return this._.cloneDeep(data);
    },
    onSort(e) {
      console.log('onSort', e)
      this.$store.commit('sortFields', e)
    },
    onTableSort(e) {
      console.log('onSort', e)
      // var items = this.tableField.filter(item => field !== item)
      this.$store.commit('sortTableFields', e)
    },
    handleDrop(item, index) {
      console.log(item, index)
      if (item) {
        const defaultName = `${item.type}_${new Date().getTime()}`
        const newItem = {
          ...item,
          label: item.title,
          prop: defaultName,
          value: item.value,
          type: item.type,
          tab: 0
        }
        console.log(newItem)
        this.$store.commit('addField', { field: newItem, index: index, tab: 0 })
      }
    },
  },
  watch: {
    sortable_items: {
      handler(val) {
        this.tablekey = 'tablekey' + new Date().getTime();
        this.setCreate();
        this.setSort();
      },
      deep: true
    }
  }
};
</script>

<style scoped>
.cont {
  position: relative;
  width: 100%;
  /* height: 117px; */
  /* background: blue; */
}
.contdiv {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  /* bottom: 40px; */
  bottom: 0;
  /* z-index: 100; */
  transition: all 0.5s;
  border-radius: 3px;
  overflow: hidden;
}
</style>
